package de.rj.urwalking.data.survey;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import de.rj.urwalking.R;

public class DropDownQuestion extends Question {

	private static final long serialVersionUID = 1L;
	private transient Spinner spinner;

	public DropDownQuestion(int id, int itemNumber, String text, int scaleId, int screen) {
		super(id, itemNumber, text, scaleId, screen);

	}

	@Override
	public View buildView(Context context, ViewGroup parent) {
		// load UI from xml layout
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.question_dropdown, parent, false);

		setQuestionText(view);
		setupSpinner(view, context);
		restoreState();

		return view;
	}

	private void setupSpinner(View view, Context context) {

		spinner = (Spinner) view.findViewById(R.id.spinner);
		ArrayAdapter<ScalePoint> adapter = new ArrayAdapter<ScalePoint>(context,
				android.R.layout.simple_spinner_dropdown_item, scalePoints);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

				int answerId = scalePoints.get(position).getIntValue();
				updateAnswer(answerId);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});

		// default value if spinner is left untouched
		int answerId = scalePoints.get(spinner.getSelectedItemPosition()).getIntValue();
		updateAnswer(answerId);
	}

	private void restoreState() {

		int answerId = getAnswer().getIntAnswer();

		for (int i = 0; i < scalePoints.size(); i++) {

			if (scalePoints.get(i).getIntValue() == answerId) {
				spinner.setSelection(i);
			}

		}

	}

	@Override
	public boolean hasBeenAnswered() {
		// always true since there is a default answer if the user doesn't do
		// anything
		return true;
	}

}
